# -*- coding: utf-8 -*-

"""
@File    : oss_utils.py
@Author  : xubin
@Time    : 2024/2/7 17:28
@Desc    :
"""
import io
import os
import minio
import chardet

from config import conf
from utils.tools import logger


class MinioClient:
    def __init__(self):
        self.client = minio.Minio(
            endpoint=conf.get_value("MINIO_ENDPOINT"),
            access_key=conf.get_value("MINIO_ACCESS_KEY"),
            secret_key=conf.get_value("MINIO_SECRET_KEY"),
            secure=eval(conf.get_value("MINIO_SECURE")),
        )

    def bucket_exists(self, bucket_name: str):
        return self.client.bucket_exists(bucket_name=bucket_name)

    def create_bucket(self, bucket_name: str):
        try:
            if not self.bucket_exists(bucket_name):
                self.client.make_bucket(bucket_name=bucket_name)

        except Exception as e:
            logger.error(f"Error creating bucket {bucket_name}: {e}")

    def upload_data(
        self,
        bucket: str,
        file_path: str,
        content_type="application/octet-stream",
    ):
        object_name = file_path.split(os.sep)[-1]

        try:
            self.create_bucket(bucket)
            self.client.fput_object(
                bucket_name=bucket,
                object_name=object_name,
                file_path=file_path,
                content_type=content_type,
            )
            logger.info(f"Success upload!")
        except Exception as e:
            logger.error(f"Error uploading to {bucket}/{object_name}: {e}")

    def upload_obj(
        self,
        bucket: str,
        object_name: str,
        file_data,
        file_size,
        content_type="application/octet-stream",
    ):
        try:
            self.create_bucket(bucket)
            self.client.put_object(
                bucket_name=bucket,
                object_name=object_name,
                data=io.BytesIO(file_data),
                length=file_size,
                content_type=content_type,
            )
            logger.info(f"Uploaded {object_name} to {bucket}")
            return True
        except Exception as e:
            logger.error(f"Error uploading to {bucket}/{object_name}: {e}")

    def download_data(self, bucket: str, object_name: str):
        try:
            if not self.bucket_exists(bucket):
                return None
            data = self.client.get_object(bucket, object_name)
            return data.read()

        except Exception as e:
            logger.error(f"Error downloading from {bucket}/{object_name}: {e}")

    def get_files(self, bucket_name):
        file_names = []
        for obj in self.client.list_objects(bucket_name):
            file_name = obj.object_name
            file_names.append(file_name)
        return file_names

    def get_txt(self, bucket_name, file_name):

        data_byte = self.client.get_object(bucket_name, file_name).data
        encoding = chardet.detect(data_byte)["encoding"]
        return data_byte.decode(encoding)


minio_client = MinioClient()
